package com.cybertron.ironhide.spider.jms.listener;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cybertron.ironhide.spider.SpiderListenerAdaptor;
import com.cybertron.ironhide.spider.domain.Product;
import com.cybertron.ironhide.spider.fetcher.FetchResult;
import com.cybertron.ironhide.spider.jms.sender.ProductMessageSender;
import com.cybertron.ironhide.spider.task.Task;

@Component("ecSpiderListenerAdaptor")
public class ECSpiderListenerAdaptor extends SpiderListenerAdaptor {

	@Autowired(required = false)
	private ProductMessageSender productMessageSender;

	public ECSpiderListenerAdaptor() {
		super();
	}

	private final static Logger logger = Logger
			.getLogger(ECSpiderListenerAdaptor.class);

	public void onFetch(Thread thread, Task task, FetchResult result) {
		logger.debug("fetch result ->" + result + " from -> " + task.sourceUrl);
	}

	public void onDupRemoval(Thread currentThread, Task task,
			Collection<Task> validTasks) {
		for (Task t : validTasks) {
			logger.debug("dupremove " + t.url + " from>" + t.sourceUrl);
		}
	}

	public void onError(Thread thread, Task task, String err, Throwable e) {
		logger.error(e.getMessage(), e);
		e.printStackTrace();
	}

	public void onParse(Thread thread, Task task,
			List<Map<String, Object>> models) {
		String source = task.site.getName();
		String categoryId = task.seedUrl.getCategoryId();
		String seedId = task.seedUrl.getId();
		for (Map<String, Object> page : models) {
			saveProduct(source, categoryId, seedId, page);
		}
	}

	private Double getPrice(String text) {
		if (StringUtils.isBlank(text)) {
			return null;
		}
		DecimalFormat format = new DecimalFormat("#,###.00");
		try {
			Number n = format.parse(text);
			return n.doubleValue();
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	private void saveProduct(String source, String categoryId, String seedId,
			Map<String, Object> page) {
		String targetUrl = null;
		if ("amazon".equals(source)) {
			targetUrl = StringUtils.substringBeforeLast(
					String.valueOf(page.get("task_url")), "/");
			targetUrl = StringUtils.substringBefore(
					String.valueOf(page.get("task_url")), "/ref");
		} else if ("eBay".equals(source)) {
			targetUrl = StringUtils.substringBeforeLast(
					String.valueOf(page.get("task_url")), "?");
		} else {
			targetUrl = String.valueOf(page.get("task_url"));
		}
		String sourceUrl = page.get("source_url") == null ? null
				: (String) page.get("source_url");
		String title = page.get("title") == null ? null : (String) page
				.get("title");
		String image = page.get("image") == null ? null : (String) page
				.get("image");
		String keywords = page.get("keywords") == null ? null : (String) page
				.get("keywords");
		String description = page.get("description") == null ? null
				: (String) page.get("description");
		Double price = getPrice(page.get("price") == null ? null : page.get(
				"price").toString());
		Double listPrice = getPrice(page.get("list_price") == null ? null
				: page.get("list_price").toString());
		Boolean freeShipping = StringUtils.isBlank(String.valueOf(page
				.get("free_shipping"))) ? false : true;
		String summary = page.get("summary") == null ? null : (String) page
				.get("summary");

		if (sourceUrl.equals(targetUrl)) {
			return;
		}
		if (title == null) {
			return;
		}
		if (price == null || price == 0) {
			return;
		}
		Product product = new Product(categoryId, seedId, targetUrl, sourceUrl,
				freeShipping, title, keywords, description, image, price,
				listPrice, source, summary);
		productMessageSender.sendMsg(product);
	}
}
